package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.mapper.BaseAttrInfoMapper;
import com.atguigu.gmall.product.model.BaseAttrInfo;
import com.atguigu.gmall.product.model.BaseAttrValue;
import com.atguigu.gmall.product.service.BaseAttrInfoService;
import com.atguigu.gmall.product.service.BaseAttrValueService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author terminal
 * @since 2023-06-05 18:55
 */
@Service
@Transactional
public class BaseAttrInfoServiceImpl extends ServiceImpl<BaseAttrInfoMapper,
        BaseAttrInfo> implements BaseAttrInfoService {

    @Resource
    private BaseAttrValueService baseAttrValueService;

    /**
     * 根据1,2,3级分类ID查询分类下关联平台属性列表(包含平台属性值)
     *
     * @param category1Id 一级分类ID
     * @param category2Id 二级分类ID
     * @param category3Id 三级分类ID
     * @return
     */
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {

        return this.baseMapper.attrInfoList(category1Id, category2Id, category3Id);
    }

    /**
     * 保存/修改平台属性以及平台属性值列表
     *
     * @param baseAttrInfo
     * @return
     */
    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        // 先看有没有id 判一下添加还是修改
        if (baseAttrInfo.getId() == null) {
            // this是指继承的ServiceImpl
            this.save(baseAttrInfo);
            // 添加属性值的方法 两个新增和修改都得用 就直接提出去了
            this.saveBaseAttrInfo(baseAttrInfo);
        } else {
            //修改 先删除 再新增
            this.updateById(baseAttrInfo);
            LambdaQueryWrapper<BaseAttrValue> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BaseAttrValue::getAttrId, baseAttrInfo.getId());
            baseAttrValueService.remove(queryWrapper);
            saveBaseAttrInfo(baseAttrInfo);
        }
    }

    /**
     * 批量新增平台属性值 辅助上面的新增和修改方法的
     *
     * @param baseAttrInfo
     */
    private void saveBaseAttrInfo(BaseAttrInfo baseAttrInfo) {
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if (!CollectionUtils.isEmpty(attrValueList)) {
            attrValueList.stream().forEach(baseAttrValue -> {
                baseAttrValue.setAttrId(baseAttrInfo.getId());
            });
            baseAttrValueService.saveBatch(attrValueList);
        }
    }

    /**
     * 根据平台属性ID 查询平台属性值列表
     *
     * @param attrId
     * @return
     */
    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        LambdaQueryWrapper<BaseAttrValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseAttrValue::getAttrId,attrId);
        return baseAttrValueService.list(queryWrapper);
    }
}
